package com.up.jiasai.spring.aspect;
import com.up.vms.application.base.utils.JsonUtils;
import com.up.vms.application.base.utils.RequestUtils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class WebLogAspect {
    ThreadLocal<Long> startTime = new ThreadLocal();
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public WebLogAspect() {
        this.logger.info("<WebLogAspect> AOP init....");
    }

    @Pointcut("execution(* com.up.*.*.*.controller.*Controller.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        this.logger.info("=======================================<WebLogAspect>=======================================");
        this.startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        this.logger.info("<WebLogAspect> URL : " + request.getRequestURL().toString());
        this.logger.info("<WebLogAspect> HTTP_METHOD : " + request.getMethod());
        this.logger.info("<WebLogAspect> IP : " + RequestUtils.getRemoteIp(request));
        this.logger.info("<WebLogAspect> CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        this.logger.info("<WebLogAspect> ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        this.logger.info("<WebLogAspect> RESPONSE : " + JsonUtils.toStringNoEx(ret));
        this.logger.info("<WebLogAspect> SPEND TIME : " + (System.currentTimeMillis() - ((Long) this.startTime.get()).longValue()));
        this.logger.info("");
    }
}
